﻿using System;
using System.Collections.Generic;

namespace Jayden.Dll.Core
{
	public class Factory
	{
		private Configuration m_Configuration;
		private Dictionary<string, Type> m_Types = new Dictionary<string, Type>();

		public Factory(Configuration config)
		{
			if (config == null)
				throw new ArgumentNullException("config");
			m_Configuration = config;
		}

		private string GetTypeReference(string key)
		{
			string xpath = string.Format(string.Format("Impl[@key=\"{0}\"]/@type", key));
			string typeReference = m_Configuration.GetValue(xpath);
			return typeReference;
		}

		public object NewInstance(string key)
		{
			Type type;
			if (!m_Types.TryGetValue(key, out type))
			{
				string typeReference = GetTypeReference(key);
				if (typeReference != null)
					type = Type.GetType(typeReference, true);
				else
					throw new Exception(string.Format("Unknow key in Factory: '{0}'.", key));
			}
			if(type != null)
				return Activator.CreateInstance(type);
			throw new Exception(string.Format("Invalid key in Factory: '{0}'", key));
		}

		public T NewInstance<T>() where T:class
		{
			Type interfaceType = typeof(T);
			return NewInstance(interfaceType.FullName) as T;
		}
	}
}
